# python
from flask import Blueprint, request, jsonify, current_app

from ..common.AESUtil import encrypt_aes, decrypt_aes
from ..common.Result import response, response_failure
from ..models.user import User, user_fields
from .. import db

user_bp = Blueprint('user_bp', __name__)

from werkzeug.utils import secure_filename
import os
from flask import send_from_directory
import hashlib

UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), '..', 'photo', 'food')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
current_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

DEFAULT_FOLDER = os.path.join(os.path.dirname(__file__), '..', 'photo', 'default')
current_app.config['DEFAULT_FOLDER'] = DEFAULT_FOLDER
@user_bp.route('/photo/default/<filename>')
def default_pic(filename):
    return send_from_directory(current_app.config['DEFAULT_FOLDER'], filename)

@user_bp.route('/photo/avatar/<filename>')
def uploaded_file(filename):
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)



@user_bp.route('/avatar/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return response_failure(msg="没有文件部分")
    file = request.files['file']
    if file.filename == '':
        return response_failure(msg="没有选择文件")
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        md5_filename = hashlib.md5(filename.encode()).hexdigest() + os.path.splitext(filename)[1]
        file.save(os.path.join(UPLOAD_FOLDER, md5_filename))
        return response(data={'filename': 'http://127.0.0.1:5000/photo/avatar/' + md5_filename}, msg="文件上传成功")
    return response_failure(msg="不允许的文件类型")


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# 生成 token
def generate_token(userid: str, role: str) -> str:
    # 拼接 userid 和 role
    data_to_encrypt = f"{userid}:{role}"
    # 加密并生成 token
    encrypted_token = encrypt_aes(data_to_encrypt)

    return encrypted_token


# 解析 token
def parse_token(token: str) -> tuple:
    # 解密 token
    decrypted_data = decrypt_aes(token)
    # 拆分解密后的字符串
    userid, role = decrypted_data.split(":")

    return userid, role


@user_bp.route('/user/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    user = User.query.filter_by(username=username).first()
    if user is None:
        return response_failure(msg="用户名不存在")
    if user.password != password:
        return response_failure(msg="密码错误")

    # 如果登录成功，生成 token
    userid = str(user.id)
    role = user.role  # 假设 role 字段在 User 模型中

    # 生成 token
    token = generate_token(userid, role)

    # 将用户信息和 token 一起返回
    user_data = user.to_dict()
    user_data['token'] = token

    return response(data=user_data, msg="登录成功！")


@user_bp.route('/user/register', methods=['POST'])
def register_user():
    data = request.get_json()
    data['create_time'] = db.func.now()
    user = User(**data)
    user.nick_name = user.username
    user.role = 0
    if user.gender == '男':
        user.avatar = 'http://127.0.0.1:5000/photo/default/male.png'
    else:
        user.avatar = 'http://127.0.0.1:5000/photo/default/female.png'
    existing_user = User.query.filter_by(username=user.username).first()
    if existing_user:
        return response_failure(msg="用户名已存在")
    db.session.add(user)
    db.session.commit()
    return response(data=user.to_dict(), msg="注册成功！")


@user_bp.route('/user/getUserInfoByToken', methods=['GET'])
def getUserInfoByToken():
    token = request.args.get('token')
    if token is None:
        return response_failure(msg="token 不存在");
    userid, role = parse_token(token)
    user = User.query.get(userid)
    return response(data=user.to_dict())


@user_bp.route('/user', methods=['POST'])
def create_user():
    data = request.get_json()
    data['create_time'] = db.func.now()
    user = User(**data)
    existing_user = User.query.filter_by(username=user.username).first()
    if existing_user:
        return response_failure(msg="用户名已存在")
    db.session.add(user)
    db.session.commit()
    return response(data=user.to_dict(), msg="注册成功！")


@user_bp.route('/user/<int:id>', methods=['GET'])
def get_user(id):
    user = User.query.get(id)
    if user is None:
        return response_failure(msg="没有这个用户")
    return response(data=user.to_dict())


@user_bp.route('/user/<int:id>', methods=['PUT'])
def update_user(id):
    data = request.get_json()
    user = User.query.get_or_404(id)
    # 更新用户属性
    for key, value in data.items():
        if hasattr(user, key):
            setattr(user, key, value)

    db.session.commit()
    return response(msg='用户信息更新成功！')


@user_bp.route('/user/<int:id>', methods=['DELETE'])
def delete_user(id):
    user = User.query.get_or_404(id)
    db.session.delete(user)
    db.session.commit()
    return response(msg='用户信息删除成功！')


@user_bp.route('/user/page', methods=['POST'])
def page_users():
    data = request.get_json()
    page = data.get('page', 1)
    per_page = data.get('per_page', 10)
    username = data.get('username', None)
    nick_name = data.get('nick_name', None)
    role = data.get('role', None)

    query = User.query

    if username:
        query = query.filter(User.username.like(f'%{username}%'))

    if nick_name:
        query = query.filter(User.nick_name.like(f'%{nick_name}%'))

    if role:
        query = query.filter(User.role == role)

    users = query.paginate(page=page, per_page=per_page, error_out=False)
    users_list = [user.to_dict() for user in users.items]
    return response(data={
        'items': users_list,
        'total': users.total,
        'per_page': users.per_page,
        'current': users.page
    })

@user_bp.route('/user/delete', methods=['DELETE'])
def delete_users():
    data = request.get_json()
    ids = data.get('ids', [])

    for id in ids:
        user = User.query.get(id)
        db.session.delete(user)
    db.session.commit()
    return response(msg='用户信息删除成功！')

@user_bp.route('/user/updatePassword/<int:id>', methods=['PUT'])
def update_password(id):
    data = request.get_json()
    user = User.query.get_or_404(id)
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    if user.password != old_password:
        return response_failure(msg="旧密码错误")
    user.password = new_password
    db.session.commit()
    return response(msg='密码修改成功！')